package jrain.fw.dao.common.parser.bean;

import java.util.Map;

import jrain.fw.core.dao.bean.SqlBean;

public class IfExpression extends SqlExpression {

	private ConditionBean condition;
	private SqlExpression ifExpr;
	private SqlExpression elseExpr;

	public ConditionBean getCondition() {
		return condition;
	}

	public void setCondition(ConditionBean condition) {
		this.condition = condition;
	}

	public SqlExpression getIfExpr() {
		return ifExpr;
	}

	public void setIfExpr(SqlExpression ifExpr) {
		this.ifExpr = ifExpr;
	}

	public SqlExpression getElseExpr() {
		return elseExpr;
	}

	public void setElseExpr(SqlExpression elseExpr) {
		this.elseExpr = elseExpr;
	}

	@Override
	public String calcExpression() {
		StringBuilder sb = new StringBuilder();
		sb.append("if(");
		sb.append(condition);
		sb.append("){");
		sb.append(ifExpr.calcExpression());
		sb.append("}else{");
		sb.append(elseExpr.calcExpression());
		sb.append("}");
		return sb.toString();
	}

	@Override
	public SqlBean calcSql(Map<String, Object> sqlCfg, Map<String, Object> data, Map<String, Object> ctx) {
		if (condition.calc(data)) {
			return ifExpr.calcSql(sqlCfg, data, ctx);
		} else {
			if (elseExpr == null) {
				return new SqlBean();
			} else {
				return elseExpr.calcSql(sqlCfg, data, ctx);
			}
		}
	}

}
